package com.dvj.demo.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ElasticsearchConfig
 *
 * @author Dvj
 * @date 2021/7/9 15:43
 */
@Configuration
public class ElasticsearchConfig {
    @Value("${dvj.elasticsearch.host-list}")
    private String hostList;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        String[] hosts = hostList.split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length];
        for (int i = 0; i < hosts.length; i++) {
            String[] h = hosts[i].split(":");
            httpHosts[i] = new HttpHost(h[0], Integer.parseInt(h[1]), "http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }
}
